import * as THREE from 'three'
import { DIMENSIONS, LEG_STRUCTURES, PANEL_TYPES } from './constants'

export const createFourWayPallet = (scene, material, params) => {
  
  const palletGroup = scene.getPalletGroup() 
  const {
    BOARD_THICKNESS,
    BEAM_WIDTH,
    BEAM_HEIGHT,
    BLOCK_WIDTH 
  } = DIMENSIONS 

  // 尺寸标准化 
  const scaledLength = params.boardLength / 100 
  const scaledWidth = params.beamLength / 100 
  const scaledWingWidth = (params.tf_boardwing || 0) / 100 
  
  // 🔥 修复1：正确处理垫块高度
  let scaledBlockHeight
  if (params.customize === 0) {
    // 二手模式使用标准高度
    scaledBlockHeight = 0.1 // 10cm 标准高度
  } else {
    // 定制模式根据 useCustomHeight 决定
    if (params.useCustomHeight) {
      scaledBlockHeight = Math.min(0.13, Math.max(0.09, params.f_blockheight / 100))
    } else {
      scaledBlockHeight = 0.1 // 通用标准高度
    }
  }
  
  const boardSpacing = scaledBlockHeight + BOARD_THICKNESS 



  // ==================== 1. 创建腿部结构A ====================
  const createLegTypeA = (xPos, zPos) => {
    const legGroup = new THREE.Group()
    legGroup.position.set(xPos, -BEAM_HEIGHT / 2, zPos)
    palletGroup.add(legGroup) 

    // 木板条参数（沿Z轴延伸）
    const boardLength = scaledWidth 

    // 下木板条 
    const bottomBoard = new THREE.Mesh(
      new THREE.BoxGeometry(BEAM_WIDTH + 0.04, BOARD_THICKNESS, boardLength),
      material 
    )
    bottomBoard.position.set(0, -boardSpacing / 2, 0)
    bottomBoard.castShadow = bottomBoard.receiveShadow = true 
    legGroup.add(bottomBoard) 

    // 上木板条 
    const topBoard = new THREE.Mesh(
      new THREE.BoxGeometry(BEAM_WIDTH + 0.04, BOARD_THICKNESS, boardLength),
      material 
    )
    topBoard.position.set(0, boardSpacing / 2, 0)
    topBoard.castShadow = topBoard.receiveShadow = true 
    legGroup.add(topBoard) 

    // 3个垫块（沿Z轴排列，与木板条同向）
    const blockPositions = [
      -boardLength / 2 + BLOCK_WIDTH / 2,  // 前端 
      0,                                // 中间 
      boardLength / 2 - BLOCK_WIDTH / 2     // 后端 
    ]

    blockPositions.forEach(z => {
      const block = new THREE.Mesh(
        new THREE.BoxGeometry(BLOCK_WIDTH, scaledBlockHeight, BLOCK_WIDTH),
        material 
      )
      block.position.set(0, 0, z)
      block.rotation.y = Math.PI / 2 
      block.castShadow = block.receiveShadow = true 
      legGroup.add(block) 
    })
  }

  // ==================== 1.2. 创建腿部结构B ====================
  const createLegTypeB = (xPos, zPos, topx, topy) => {
    const legGroup = new THREE.Group()
    legGroup.position.set(zPos, -BEAM_HEIGHT / 2, xPos)
    legGroup.rotation.y = Math.PI / 2 
    palletGroup.add(legGroup) 

    // 木板条参数 
    const boardLength = scaledLength 
    const beamLength = scaledWidth 

    // 下木板条 
    const bottomBoard = new THREE.Mesh(
      new THREE.BoxGeometry(BEAM_WIDTH + 0.04, BOARD_THICKNESS, boardLength),
      material 
    )
    bottomBoard.position.set(0, -boardSpacing / 2, 0)
    bottomBoard.castShadow = bottomBoard.receiveShadow = true 
    legGroup.add(bottomBoard) 

    // 上木板条 
    const topBoard = new THREE.Mesh(
      new THREE.BoxGeometry(BEAM_WIDTH + 0.04, BOARD_THICKNESS, beamLength),
      material 
    )
    topBoard.rotation.y = Math.PI / 2 
    topBoard.castShadow = topBoard.receiveShadow = true 
    topBoard.position.set(topx, boardSpacing/2, topy)
    legGroup.add(topBoard) 

    // 3个垫块 
    const blockPositions = [
      -boardLength / 2 + BLOCK_WIDTH / 2,
      0,
      boardLength / 2 - BLOCK_WIDTH / 2 
    ]

    blockPositions.forEach(z => {
      const block = new THREE.Mesh(
        new THREE.BoxGeometry(BLOCK_WIDTH, scaledBlockHeight, BLOCK_WIDTH),
        material 
      )
      block.position.set(0, 0, z)
      block.rotation.y = Math.PI / 2 
      block.castShadow = block.receiveShadow = true 
      legGroup.add(block) 
    })
  }

  // ==================== 2. 创建腿部位置 ==================== 
  const baseLegPositionsA = [
    -scaledLength / 2 + 0.05,
    0,
    scaledLength / 2 - 0.05 
  ]

  const legPositionsA = [
    baseLegPositionsA[0] + scaledWingWidth,
    baseLegPositionsA[1],
    baseLegPositionsA[2] - scaledWingWidth 
  ]

  const baseLegPositionsB = [
    -scaledWidth / 2 + 0.05,
    0,
    scaledWidth / 2 - 0.05 
  ]

  const legPositionsB = [
    baseLegPositionsB[0],
    baseLegPositionsB[1],
    baseLegPositionsB[2]
  ]

  // ==================== 创建腿部 ==================== 

  
  // 🔥 修复2：确保彻底清理旧内容
  while (palletGroup.children.length > 0) {
    palletGroup.remove(palletGroup.children[0])
  }
  
  if (params.customize === 0) {

    legPositionsA.forEach((x) => {
      createLegTypeA(x, 0)
    })
  } else {
    // 定制状态根据选择的结构类型创建 
    if (params.f_structure === LEG_STRUCTURES.TYPE_A) {

      legPositionsA.forEach((x) => {
        createLegTypeA(x, 0)
      })
    } else if (params.f_structure === LEG_STRUCTURES.TYPE_B) {
      legPositionsB.forEach((x, index) => {
        const topy = [-0.458-(scaledLength-1)/2, 0, 0.458+(scaledLength-1)/2][index]
        const topx = [-0.45-(scaledWidth-1)/2, 0, 0.45+(scaledWidth-1)/2][index]
        createLegTypeB(x, 0, topx, topy)
      })
    } else {
      legPositionsA.forEach((x) => {
        createLegTypeA(x, 0)
      })
    }
  }

  // ==================== 3. 创建顶部面板 =================== 
  const boardHeight = BEAM_HEIGHT / 2 + BOARD_THICKNESS / 2 - 0.03 

  if (params.panel_leg === PANEL_TYPES.PLYWOOD) {
    // 胶合板模式 
    const panel = new THREE.Mesh(
      new THREE.BoxGeometry(scaledLength, BOARD_THICKNESS, scaledWidth),
      material 
    )
    panel.position.set(0, boardHeight, 0)
    panel.castShadow = panel.receiveShadow = true 
    palletGroup.add(panel) 
  } else {
    // 木条板模式 
    const boardCount = 6 
    const minBoardWidth = 0.01 
    const baseBoardWidth = 0.1 
    const minGap = 0.005 

    let boardWidth, gap 
    const totalSpace = scaledWidth 

    if (totalSpace <= boardCount * minBoardWidth) {
      boardWidth = minBoardWidth 
      gap = (totalSpace - (boardCount * boardWidth)) / (boardCount - 1)
    } else {
      boardWidth = baseBoardWidth 
      gap = (totalSpace - (boardCount * boardWidth)) / (boardCount - 1)

      if (gap < minGap) {
        gap = minGap 
        boardWidth = (totalSpace - ((boardCount - 1) * gap)) / boardCount 
      }
    }

    for (let i = 0; i < boardCount; i++) {
      const board = new THREE.Mesh(
        new THREE.BoxGeometry(scaledLength, BOARD_THICKNESS, boardWidth),
        material 
      )
      board.position.set( 
        0,
        boardHeight + (scaledBlockHeight - 0.1)/3,
        -totalSpace / 2 + boardWidth / 2 + i * (boardWidth + gap)
      )
      board.castShadow = board.receiveShadow = true 
      palletGroup.add(board) 
    }
  }

}